import { materialPage, productAdd, productDel, productPage, productUpdate } from '@/api/baseData/product';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';
import axiosInstance from '@/utils/http/api';

interface productRecord {
	extension?: Record<string, any>;
	id: string;
	createTime?: string;
	updateUser?: string;
	updateTime?: string;
	createUser?: string;
	productName?: string;
	productCode?: string;
	materialId?: string;
	category?: string;
	description?: string;
	activate?: boolean;
	isDeleted?: boolean;
	clazz?: string;
}

interface productPageResult {
	records: productRecord[];
	total: number;
	size: number;
	current: number;
	optimizeCountSql: boolean;
	searchCount: boolean;
	pageSize: number;
}

interface ApiResponse<T> {
	code: number;
	message: string;
	data: T;
}

interface PaginationParams {
	current: number;
	pageSize: number;
}

interface FormData {
	productName: string;
	productCode: string;
	materialId: string;
	category: string;
}

interface materialData {
	id: string;
	materialName: string;
}

export function useproductData() {
	const searchParam = ref({});
	const isLoading = ref(true);
	const searchFields = ref([
		{
			name: 'productName',
			label: '产品名称',
			component: 'input',
			placeholder: '',
			class: '!w-[350px]'
		},
		{
			name: 'productCode',
			label: '产品编码',
			component: 'input',
			placeholder: '',
			class: '!w-[350px]'
		}
	]);
	const pageTotal = ref(0);
	const paginatedData = ref<productRecord[]>([]);
	const paginationParams = ref<PaginationParams>({ current: 1, pageSize: 10 });
	const formData = ref<FormData>({
		productName: '',
		productCode: '',
		materialId: '',
		category: ''
	});

	// 表单实例引用
	const ruleFormRef = ref<FormInstance>();

	// 材料列表
	const materialList = ref<materialData[]>([]);

	// 验证规则
	const rules = ref<FormRules>({
		productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
		productCode: [{ required: true, message: '请输入产品编码', trigger: 'blur' }],
		materialId: [{ required: true, message: '请选择成品物料', trigger: 'change' }],
		category: [{ required: true, message: '请输入产品类别', trigger: 'blur' }]
	});
	const fetchPageData = async (params: any) => {
		isLoading.value = true;
		try {
			const response = (await productPage({
				...params,
				current: paginationParams.value.current,
				pageSize: paginationParams.value.pageSize
			})) as unknown as ApiResponse<productPageResult>;

			if (response.code === 200) {
				const { records, total } = response.data;
				paginatedData.value = records.map((item) => {
					return {
						...item.extension,
						...item
					};
				});
				pageTotal.value = total;
			} else {
				ElMessage.error(response.message);
			}
		} catch (error) {
			ElMessage.error('数据获取失败');
		} finally {
			isLoading.value = false; // 数据加载完成后设置为 false
		}
	};

	onMounted(() => {
		fetchPageData(searchParam.value);
		fetchLineData();
	});
	const fetchLineData = () => {
		// materialPage({}).then((res) => {
		//   materialList.value = res.data.records
		// })
		axiosInstance.post('/api/basedataMaterial/getAll',
			{ materialProperties: 2 }
		).then(res => {
			const { data, code, message } = res;
			if (code === 200) {
				console.log(data);
				materialList.value = data;
			}
		});
	};
	const handleSearch = () => {
		fetchPageData(searchParam.value);
	};

	const handleSizeChange = (val: number) => {
		paginationParams.value.pageSize = val;
		fetchPageData(searchParam.value);
	};

	const handleCurrentChange = (val: number) => {
		paginationParams.value.current = val;
		fetchPageData(searchParam.value);
	};

	const addproduct = async (data: Partial<productRecord>, callback: () => void) => {
		if (ruleFormRef.value) {
			await ruleFormRef.value.validate(async (valid) => {
				if (valid) {
					const url = data?.id ? productUpdate : productAdd;
					const response = (await url(data)) as unknown as ApiResponse<void>;
					if (response.code === 200) {
						if (data?.id) {
							ElMessage.success('更新成功');
						} else {
							ElMessage.success('添加成功');
						}
						fetchPageData(searchParam.value);
						callback();
					} else {
						ElMessage.error(response.message);
					}
				}
			});
		}
	};

	const deleteproduct = async (id: string) => {
		try {
			const response = (await productDel({ ids: [id] })) as unknown as ApiResponse<void>;
			if (response.code === 200) {
				ElMessage.success('删除成功');
				fetchPageData(searchParam.value);
			} else {
				ElMessage.error(response.message);
			}
		} catch (error) {
			ElMessage.error('删除失败');
		}
	};

	return {
		searchParam,
		pageTotal,
		paginatedData,
		searchFields,
		isLoading,
		handleSearch,
		handleSizeChange,
		handleCurrentChange,
		addproduct,
		deleteproduct,
		paginationParams,
		ruleFormRef,
		rules,
		formData,
		materialList
	};
}
